import React, { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { message } from 'antd';
import { myAxios } from '../axios';
import { useStore } from '../stores/index';
import './Detail.less';

const Detail = () => {
  const navigate = useNavigate();
  const { id } = useParams();
  const [loading, setLoading] = useState(false);
  const [detailData, setDetailData] = useState(null);
  const store = useStore();
  const userdata = store.userdata;

  useEffect(() => {
    if (!id) {
      navigate('/home/market');
      return;
    }
    
    const fetchHelpDetail = async () => {
      setLoading(true);
      try {
        const res = await myAxios.get(`/help/find/${id}`);
        console.log('获取到的数据:', res.data);
        if (res.data.code === 200 && res.data.data) {
          setDetailData(res.data.data);
        } else {
          message.error('获取数据失败');
          navigate('/home/market');
        }
      } catch (error) {
        console.error('获取数据失败:', error);
        message.error('获取数据失败');
        navigate('/home/market');
      } finally {
        setLoading(false);
      }
    };

    fetchHelpDetail();
  }, [id, navigate]);

  const handleReturn = () => {
    navigate('/home/market');
  };

  const handleAccept = async () => {
    if (!userdata.isTeacher) {
      message.error('只有教师才能接单');
      return;
    }

    if (!detailData.help_id) {
      message.error('缺少必要参数');
      return;
    }

    setLoading(true);
    try {
      const res = await myAxios.post('/order/create', {
        helpId: detailData.help_id,
        teacherId: userdata.id
      });

      if (res.data.code === 200) {
        message.success('接单成功！');
        navigate('/home/market');
      } else {
        message.error(res.data.message || '接单失败');
      }
    } catch (error) {
      console.error('接单失败:', error);
      message.error('发生错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return <div className="loading-container">加载中...</div>;
  }

  if (!detailData) {
    return null;
  }

  const detail = detailData;

  return (
    <div className="market-detail-container">
      <div className="detail-card">
        <div className="detail-header">
          <h1 className="title">{detail.title}</h1>
          <div className="meta-info">
            <span>发布时间: {new Date(detail.created_at).toLocaleDateString()}</span>
            <span>发布人：{detail.user_name}</span>
            <span className={`status ${detail.status}`}>
              {detail.status === 'pending' ? '进行中' : '已完成'}
            </span>
          </div>
        </div>

        <div className="detail-content">
          <div className="info-section">
            <h3>学生信息</h3>
            <div className="info-row">
              <span className="label">学生姓名:</span>
              <span className="value">{detail.full_name}</span>
            </div>
            <div className="info-row">
              <span className="label">学生性别:</span>
              <span className="value">{detail.gender === 'Male' ? '男' : '女'}</span>
            </div>
            <div className="info-row">
              <span className="label">学生年龄:</span>
              <span className="value">{detail.age}岁</span>
            </div>
            <div className="info-row">
              <span className="label">学生年级:</span>
              <span className="value">{detail.grade}</span>
            </div>
            <div className="info-row">
              <span className="label">就读学校:</span>
              <span className="value">{detail.school}</span>
            </div>
          </div>

          <div className="info-section">
            <h3>辅导信息</h3>
            <div className="info-row">
              <span className="label">科目需求:</span>
              <span className="value">{detail.subject}</span>
            </div>
            <div className="info-row">
              <span className="label">授课方式:</span>
              <span className="value">{detail.help_type === 'online' ? '线上' : '线下'}</span>
            </div>
            <div className="info-row">
              <span className="label">授课频率:</span>
              <span className="value">{detail.frequency}</span>
            </div>
            <div className="info-row">
              <span className="label">每次时长:</span>
              <span className="value">{detail.duration}</span>
            </div>
            <div className="info-row">
              <span className="label">居住区域:</span>
              <span className="value">{detail.location}</span>
            </div>
            <div className="info-row">
              <span className="label">联系方式:</span>
              <span className="value">{detail.user_phone}</span>
            </div>
            <div className="info-row">
              <span className="label">辅导奖励:</span>
              <span className="value">{detail.reward}</span>
            </div>
          </div>

          <div className="info-section">
            <h3>补充说明</h3>
            <div className="description">
              {detail.description}
            </div>
          </div>
        </div>

        <div className="detail-footer">
          {userdata.isTeacher && (<button 
            className="accept-btn"
            disabled={detail.status === 'completed' || loading}
            onClick={handleAccept}
          >
            {loading ? '处理中...' : 
             detail.status === 'completed' ? '已结束' : 
             '我要辅导ta！'}
          </button>)}
          
          <button 
            className="return-btn" 
            onClick={handleReturn}
            disabled={loading}
          >
            返回
          </button>
        </div>
      </div>
    </div>
  );
};

export default Detail;